package com.seguridad.ws.handler;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class StringComparator {

	public static boolean compare(String str1, String str2) {
	
		boolean valid = true;
		if(str1.length() != str2.length()){
			valid = false;
		}
		
		char[] array1Chars = str1.toCharArray();
		char[] array2Chars = str2.toCharArray();	
		
		for (int i = 0; i < array1Chars.length && valid; i++) {
			char c1 = array1Chars[i];
			char c2 = array2Chars[i];
			if(c1 != c2){
				valid = false;
			}
		}
		
		return valid;
	}
	
	public static boolean compare(String str1, String str2, Integer bits) {
		boolean valid = true;
		
		char[] array1Chars = getBinaryForm(str1).toCharArray();
		char[] array2Chars = getBinaryForm(str2).toCharArray();	
		
		for (int i = 0; i < array1Chars.length && i < bits && valid; i++) {
			char c1 = array1Chars[i];
			char c2 = array2Chars[i];
			if(c1 != c2){
				valid = false;
			}
		}
		
		return valid;
	}
	
	private static String getBinaryForm(String str){
		String result = "";
		try {
			byte[] bytes = Hex.decodeHex(str.toCharArray());
			StringBuilder binary = new StringBuilder();
			for (byte b : bytes)
			{
			   int val = b;
			   for (int i = 0; i < 8; i++)
			   {
			      binary.append((val & 128) == 0 ? 0 : 1);
			      val <<= 1;
			   }
			}
			result = binary.toString();

		} catch (DecoderException e) {
			e.printStackTrace();
		}
		
		
		return result;
	}

}
